<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    :width="700"
    :append-to-body="false"
    :close-on-click-modal="false"
    @close="handleClose(false)"
    :class="['center-detail', theme === 'dark' ? 'dark' : '']"
  >
    <JLForm
      ref="formRef"
      class="upload-form"
      :form-config="formConfig"
      :form-data="formData"
      :form-item-config="formItemConfig"
    >
      <template #slotDataType>
        <div class="select-data-type">
          <el-select
            v-model="formData['dataType']"
            :disabled="dataTypeDisabled"
            placeholder="请选择"
            :clearable="true"
          >
            <el-option
              v-for="option in dataTypeOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
          <el-input
            v-if="!['img', 'osgb'].includes(formData['fileType'])"
            v-model="extent"
            placeholder="请输入切图参数"
            :disabled="extentDisable"
            :maxlength="200"
            @change="changeExtent"
            type="text"
            :clearable="true"
          />
        </div>
      </template>
      <!-- 分类 -->
      <template #slotClassification>
        <!-- :visible="visibleCategoryTree" -->
        <el-popover
          :popper-class="['custom-popover', theme === 'dark' ? 'dark' : '']"
          placement="bottom-start"
          trigger="click"
          width="570"
          :teleported="false"
          :disabled="categoryDisabled"
        >
          <template #reference>
            <div
              class="category-input"
              :class="categoryDisabled ? 'disabled' : ''"
              @click="visibleCategoryTree = true"
            >
              <span v-if="fileCategoryName">{{ fileCategoryName }}</span>
              <span v-else class="placeholder">请选择分类</span>
              <SvgIcon class="svg-arrow" icon-class="ic_向下" />
            </div>
          </template>
          <!-- 移动至 tree -->
          <el-tree
            :data="categoryTree"
            :icon="getSvgIcon('ic_向右')"
            node-key="categoryId"
            show-checkbox
            :check-strictly="false"
            :expand-on-click-node="true"
            :default-checked-keys="checkedKeys"
            :props="{
              children: 'children',
              label: 'categoryName',
              value: 'categoryId',
            }"
            ref="treeRef"
            @node-click="handleNodeClick"
          />
        </el-popover>
      </template>

      <!-- 数据处理 --- 1STP/STEP、DXF、OBJ、FBX、3DS、DGN、SKP -->
      <template #slotDataProcessing>
        <div class="data-processing">
          <div class="data-processing-select">
            <div class="select-term">
              <label>
                转换为
                <el-tooltip
                  effect="light"
                  content="与3dtiles不同的是，glb支持材质替换"
                  placement="top-start"
                >
                  <SvgIcon icon-class="问"></SvgIcon>
                </el-tooltip>
              </label>
              <el-select v-model="changeType" placeholder="请选择">
                <el-option label="GLTF/GLB" value="gltf/glb" />
                <el-option label="3DTILES" value="3dtiles" />
              </el-select>
            </div>
            <div class="select-term" v-if="!['3dxml', 'skp'].includes(formData.fileType)">
              <label>模型精度</label>
              <el-select v-model="formData.ModelPrecision" placeholder="请选择">
                <el-option
                  v-for="(item, i) in ModelPrecisionOptionsArr"
                  :label="item.label"
                  :value="item.value"
                  :key="i"
                />
              </el-select>
            </div>
          </div>
          <div class="data-processing-switch">
            <div class="switch-term">
              <label>Draco 压缩数据</label>
              <el-switch v-model="formData.IsDraco" style="--el-switch-on-color: #0560fd" />
            </div>
            <div class="switch-term">
              <label>构件属性</label>
              <el-switch
                v-model="formData.IsExportComponent"
                style="--el-switch-on-color: #0560fd"
              />
            </div>
          </div>
        </div>
      </template>

      <template #slotLeftPosition>
        <div class="position-input">
          <el-input
            v-model="formData.leftPosition.longitude"
            placeholder="请输入经度坐标"
            :maxlength="200"
            type="text"
            :clearable="true"
          />
          <el-input
            v-model="formData.leftPosition.latitude"
            placeholder="请输入纬度坐标"
            :maxlength="200"
            type="text"
            :clearable="true"
          />
        </div>
      </template>

      <template #slotRightPosition>
        <div class="position-input">
          <el-input
            v-model="formData.rightPosition.longitude"
            placeholder="请输入经度坐标"
            :maxlength="200"
            type="text"
            :clearable="true"
          />
          <el-input
            v-model="formData.rightPosition.latitude"
            placeholder="请输入纬度坐标"
            :maxlength="200"
            type="text"
            :clearable="true"
          />
        </div>
      </template>

      <!-- 数据格式 -->
      <template #slotFileType="{ key }">
        <div class="disabled-input" v-if="props.resource">
          {{
            ResourceFileType[getFileType(props.resource.fileType)] &&
            ResourceFileType[getFileType(props.resource.fileType)].value
          }}
        </div>
        <template v-else>
          <el-select
            class="jl-form-control"
            v-model="formData.fileType"
            :disabled="isFileTypeSelectDisable"
            popper-class="file-type-select"
            :popper-append-to-body="false"
            :teleported="false"
          >
            <el-option
              v-for="option in getFormItemByKey(key).options"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            >
              <template #default>
                <div class="select-item">
                  <div class="select-item-value">{{ option.label }}</div>
                  <div class="select-item-tips">{{ fileTypeTipsMap[option.value] }}</div>
                  <SvgIcon class="svg-class" icon-class="ic_xuanzhong" />
                </div>
              </template>
            </el-option>
          </el-select>
          <span>{{ fileTypeTipsMap[formData.fileType] }}</span>
        </template>
      </template>

      <!-- 资源文件 -->
      <template #slotResUrl>
        <div class="url-wrap" v-if="props.resource && !isReUpload && !isEditTypeUpload">
          <div class="disabled-input points">
            {{ resUrl }}
          </div>
          <div class="btn" @click="copyText(resUrl)">复制</div>
        </div>
        <template v-else>
          <el-radio-group v-model="uploadOptions" class="ml-4" @change="uploadOptionsChange">
            <el-radio label="1" size="large">本地上传</el-radio>
            <el-radio label="2" size="large">
              大文件上传
              <el-tooltip
                effect="light"
                content="请先让运维人员把大文件复制到服务器的特定文件夹,然后再从下拉菜单中选择."
                placement="top-start"
              >
                <SvgIcon icon-class="问" class="custom-radio-svg"></SvgIcon>
              </el-tooltip>
            </el-radio>
          </el-radio-group>
          <div class="local-upload" v-if="uploadOptions === '1'">
            <el-upload
              ref="uploadRef"
              action="#"
              class="upload-res-file"
              :limit="1"
              drag
              :accept="acceptData"
              :show-file-list="false"
              :before-upload="beforeUpload"
            >
              <template #default>
                <div class="up-load-res-file">
                  <SvgIcon icon-class="ic_shangchuan" />
                  <div class="el-upload__text">将文件拖到这里，或点击上传</div>
                  <div class="el-upload__tip">
                    仅支持单文件或压缩包（zip、rar）,文件大小不超过 3 G
                  </div>
                </div>
              </template>
            </el-upload>
            <div class="large-file" v-if="resFileList.length">
              <div class="file">
                <SvgIcon icon-class="ic_file"> </SvgIcon>
                {{ resFileList[0].name }}
                <SvgIcon class="close-icon" icon-class="ic_close" @click="removeFile"> </SvgIcon>
              </div>
              <el-progress :percentage="resFileList[0].md5Percentage" :show-text="false" />
            </div>
          </div>
          <div class="large-files-upload" v-else>
            <el-popover
              :popper-class="['custom-popover', theme === 'dark' ? 'dark' : '']"
              placement="bottom-start"
              trigger="click"
              width="570"
              :teleported="false"
              :disabled="categoryDisabled"
            >
              <template #reference>
                <div class="category-input" @click="visibleCategoryTree = true">
                  <span v-if="filePathCurrentObj.name">{{ filePathCurrentObj.name }}</span>
                  <span v-else class="placeholder">请选择文件</span>
                  <SvgIcon class="svg-arrow" icon-class="ic_向下" />
                </div>
              </template>
              <!-- 移动至 tree -->
              <el-tree
                :data="treeData"
                :icon="getSvgIcon('ic_向右')"
                node-key="categoryId"
                show-checkbox
                :check-strictly="false"
                :expand-on-click-node="true"
                :default-checked-keys="checkedKeys"
                :props="{
                  children: 'children',
                  label: 'name',
                  value: 'value',
                }"
                ref="treeRef"
                @current-change="filePathChange"
              />
            </el-popover>
          </div>
          <el-input v-model="formData.resUrl" class="none"></el-input>
        </template>
      </template>

      <template #slotResCover>
        <el-upload
          :show-file-list="false"
          action="#"
          :before-upload="beforeCoverUpload"
          :disabled="isReUpload"
        >
          <el-image v-if="formData.resCover" :src="getResPath(formData.resCover)" class="avatar" />
          <div v-else class="cover-up-icon" :class="isReUpload ? 'is-disabled' : ''">
            <SvgIcon icon-class="ic_up_cover"> </SvgIcon>
          </div>
        </el-upload>
      </template>
    </JLForm>
    <template #footer>
      <span class="dialog-footer">
        <el-button class="close" @click="closeChange">取消</el-button>
        <el-button color="#0560FD" type="primary" @click="save">确定</el-button>
      </span>
    </template>
  </el-dialog>
  <ProgressDialog
    v-if="upResourceDialogShow"
    @close-handle="handleClose(true)"
    :resource-id="resourceId"
    :trans-id="transId"
    :resource-name="resourceName"
    :get-file="getFile"
    :file-size="fileSize"
    :upload-method="uploadMethod"
  ></ProgressDialog>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { create } from './composables/create';
import { JLForm } from '@jl/element-plus';
import { ElMessage } from 'element-plus';
import { replaceRecord, resUploadParam, updateResource, handleLocalFile } from '@/api/resource';
import { IResource } from '@/api/resource/types';
import { commonUpload } from '@/api/common';
import { CommonUploadResp } from '@/api/common/types';
import { ResourceFileType, updatedFileFormat, updatedImgFormat } from '@/views/enum/common';
import ProgressDialog from './ProgressDialog.vue';
import { messageUtil } from '@jl/element-plus/utils';
import SparkMD5 from 'spark-md5';
import { confirmAgain, copyText } from '@/utils';
import { getResPath } from '@/utils/cimup';
import { useRequest } from '@jl/common/composable';
import { getSvgIcon } from '@/components/svg-icon';

interface IProps {
  resource: null | IResource;
  fileType: string;
  isReUpload: boolean;
  categoryId: string;
  categoryDisabled: boolean;
  theme: string;
}

const props = withDefaults(defineProps<IProps>(), {
  resource: null,
  isReUpload: false,
  categoryId: '',
  categoryDisabled: false, // 分类
  fileType: '', // 数据格式
  theme: 'light',
});
const {
  formRef,
  formConfig,
  formData,
  treeData,
  fileCurrentObj,
  ModelPrecisionOptionsArr,
  uploadOptions,
  formItemConfig,
  categoryTree,
  changeType,
  fileCategoryName,
  filePathCurrentObj,
  getCategoryTree,
  filePathChange,
  uploadOptionsChange,
  getFormItemByKey,
  fileTypeTipsMap,
} = create();
// const categoryTree = ref<any>([]);
const dialogVisible = ref<boolean>(true);
const dialogTitle = ref<string>('上传资源');
const emit = defineEmits(['closeHandle']);
const upResourceDialogShow = ref(false);
const resFileList = ref<any>([]);
const resourceId = ref<string>('');
const transId = ref<string>('');
const resourceName = ref<string>('');
const uploadRef = ref();
let fileIns: any = null;
const fileSize = ref();
const treeRef = ref<any>(null);
const checkedKeys = ref<any>([]);
const uploadMethod = ref<string>('local');

// 分类
const visibleCategoryTree = ref<boolean>(false);
const handleNodeClick = (data: any) => {
  treeRef.value!.setCheckedKeys([], false);
  if (!['底板', '模型', '分类'].includes(data.categoryName)) {
    visibleCategoryTree.value = false;
    fileCategoryName.value = data.categoryName;
    formData.value.fileCategoryId = data.categoryId;
    checkedKeys.value = [data.categoryId];
  }
};
/**
 * 切片大小
 */
const SIZE = 50 * 1024 * 1024;
const resUrl = computed(() => {
  if (!props.resource) return '';
  const pathMap: any = {
    development: 'gis',
    production: 'gis',
    testing: 'play',
  };
  const NODE_ENV: any = process.env.NODE_ENV;
  return props.resource.resUrl
    ? `${window.location.origin}/${pathMap[NODE_ENV]}/${props.resource.resUrl}`
    : '';
});
const isFileTypeSelectDisable = computed<boolean>(() => {
  return !!props.fileType;
});

// 数据选择是否被禁用
const dataTypeDisabled = computed<boolean>(() => {
  return formItemConfig.value.find((v: any) => v.key === 'dataType')?.disabled || false;
});
const dataTypeOptions = computed(() => {
  return formItemConfig.value.find((v: any) => v.key === 'dataType')?.options || [];
});
// 影像数据
const extent = ref('');
const extentDisable = computed<boolean>(() => {
  if (props.isReUpload) {
    return true;
  }
  if (
    formData.value.fileType === ResourceFileType['tif-dom'].code &&
    (formData.value?.dataType === '2' || formData.value?.dataType === '3')
  ) {
    return false;
  }
  if (
    formData.value.fileType === ResourceFileType['tif-dem'].code &&
    formData.value?.dataType === '2'
  ) {
    return false;
  }
  return true;
});

const changeExtent = () => {};

// 上传
const beforeUpload = async (file: any) => {
  const fileSuffix = file.name.substring(file.name.lastIndexOf('.'));
  if (!acceptData.value.split(',').includes(fileSuffix)) {
    ElMessage.warning('文件格式错误');
    return false;
  }
  if (file.size / 1024 / 1024 / 1024 > 50) {
    ElMessage.warning('文件大小不能超过50G');
    return false;
  }
  resFileList.value = [];
  console.log('重新复制');
  const chunks = createFileChunk(file);
  resFileList.value = [
    {
      name: file.name,
      size: file.size,
      chunks: chunks,
      md5Code: '',
      md5Percentage: 0,
    },
  ];

  formData.value.resUrl = file.name;
  fileIns = chunks;
  fileSize.value = file.size;
  resFileList.value[0].md5Code = await calculateHashSync(chunks);
  console.log(resFileList.value[0].md5Code);
  return false;
};

const createFileChunk = (file: any, size = SIZE) => {
  const chunks = [];
  let cur = 0;
  while (cur < file.size) {
    chunks.push({ file: file.slice(cur, cur + size) });
    cur += size;
  }

  return chunks;
};
const calculateHashSync = (chunks: any) => {
  return new Promise((resolve) => {
    const spark = new SparkMD5.ArrayBuffer();
    let count = 0;
    const loadNext = (index: number) => {
      const reader = new FileReader();
      reader.readAsArrayBuffer(chunks[index].file);
      reader.onload = (e: any) => {
        // 累加器 不能依赖index，
        count++;
        // 增量计算md5
        spark.append(e.target.result);
        if (count === chunks.length) {
          // 通知主线程，计算结束
          if (resFileList.value.length !== 0) {
            resolve(spark.end());
          }
          resFileList.value[0].md5Percentage = 100;
        } else {
          if (resFileList.value.length !== 0) {
            // 每个区块计算结束，通知进度即可
            resFileList.value[0].md5Percentage += 100 / chunks.length;
            // 计算下一个
            loadNext(count);
          }
        }
      };
    };
    loadNext(0);
  });
};

const removeFile = () => {
  resFileList.value = [];
  formData.value.resUrl = '';
  fileIns = null;
  fileSize.value = 0;
};

const beforeCoverUpload = async (file: any) => {
  const fileSuffix = file.name.substring(file.name.lastIndexOf('.'));
  if (!['.jpg', '.png'].includes(fileSuffix)) {
    ElMessage.warning('封面格式错误');
    return false;
  }
  const res: CommonUploadResp = await commonUpload(file);
  formData.value.resCover = res.files[0].refAddress;
  return false;
};

const save = () => {
  formRef.value?.getInstance().validate((valid, fields) => {
    if (valid) {
      if (resFileList.value.length > 0 && resFileList.value[0].md5Code === '') {
        ElMessage.warning('正在计算文件Md5,请稍后');
        return;
      }
      if (props.resource) {
        if (props.isReUpload) {
          if (props.resource.md5Code === resFileList.value[0].md5Code) {
            resourceId.value = props.resource.resourceId;
            transId.value = props.resource.transId;
            resourceName.value = formData.value.fileResName;
            upResourceDialogShow.value = true;
          } else {
            showReplaceConfim();
          }
        } else {
          update();
        }
      } else {
        add();
      }
    }
  });
};

const showReplaceConfim = async () => {
  const flag = await confirmAgain(
    '温馨提示',
    '该文件非上次上传的文件，是否继续上传？',
    '确定',
    '取消'
  );
  if (flag) {
    replace();
  }
};

const replace = () => {
  const fData = new FormData();
  if (props.resource) {
    fData.set('resourceId', props.resource.resourceId);
    fData.set('fileName', resFileList.value[0].name);
    fData.set('fileSize', resFileList.value[0].size);
    fData.set('fileResName', props.resource.fileResName);
    fData.set('fileType', formData.value.fileType);
    fData.set('matDesp', props.resource.matDesp);
    fData.set('resCover', props.resource.resUrl);
    fData.set('sliceCout', resFileList.value[0].chunks.length);
    fData.set('defSliceSize', SIZE + '');
    fData.set('md5Code', resFileList.value[0].md5Code);
    // const param = {
    //   resourceId: props.resource.resourceId,
    //   fileName: resFileList.value[0].name,
    //   fileSize: resFileList.value[0].size,
    //   fileResName: props.resource.fileResName,
    //   fileType: formData.value.fileType,
    //   configJson: props.resource.configJson,
    //   matDesp: props.resource.matDesp,
    //   resCover: props.resource.resUrl,
    //   sliceCout: resFileList.value[0].chunks.length,
    //   defSliceSize: SIZE,
    //   md5Code: resFileList.value[0].md5Code,
    // };
    const param = {
      data: fData,
    };

    replaceRecord(param).then((res: any) => {
      if (props.resource) {
        resourceId.value = props.resource.resourceId;
        transId.value = props.resource.transId;
        resourceName.value = props.resource.fileResName;
        upResourceDialogShow.value = true;
      }
    });
  }
};

// 更新
const update = () => {
  if (props.resource) {
    const fData = new FormData();
    fData.set('resourceId', props.resource.resourceId);
    fData.set('fileResName', formData.value.fileResName);
    fData.set('matDesp', formData.value.matDesp);
    fData.set('matDesp', formData.value.matDesp);
    fData.set('resCover', formData.value.resCover);
    fData.set('categoryId', formData.value.fileCategoryId);
    updateResource({ data: fData }).then((res: any) => {
      messageUtil.success('更新成功');
      handleClose(true);
    });
  }
};
// 处理本地文件
const { run: LocalFileRun, data: LocalFileData } = useRequest<any, any>(handleLocalFile, {});

// 新增
const add = () => {
  let configJson = null;
  if (formData.value.fileType === 'osgb' && formData.value.dataType === '2') {
    configJson = {
      IsChange: true,
      Format: '3dtiles',
    };
  }
  if (formData.value.fileType === 'img' && formData.value.dataType === '2') {
    configJson = {
      leftLongitude: Number(formData.value.leftPosition.longitude),
      leftLatitude: Number(formData.value.leftPosition.latitude),
      rightLongitude: Number(formData.value.rightPosition.longitude),
      rightLatitude: Number(formData.value.rightPosition.latitude),
    };
  }
  if (formData.value.fileType === 'tif-dom') {
    // Extent: Xmin, Ymin, Xmax, Ymax(左下角，右上角)
    // 直接上传： null
    // xyz切图: {IsHandle: true,Method: 'XyzCut',Extent: '783393.4481,783599.4329,3514950.4786,3515523.8981 [EPSG:32650]'}
    // 图层发布: configJson = {IsHandle: true,Method: 'LayerRele',Extent: ''};
    if (formData.value.dataType === '2') {
      configJson = {
        IsHandle: true,
        Method: 'XyzCut',
        Extent: extent.value,
      };
      if (!extent.value.includes('[EPSG:4326]')) {
        ElMessage.warning('Extent坐标系不正确');
        return false;
      }
      // let extentFlag = true;
      // const inRange = (min: number, max: number, num: number) => {
      //   return num >= min && num <= max;
      // };
      // const Extent = getExtent(extent.value).map((v: string) => Number(v));
      // Extent目前不做校验
      // if (Extent.length === 4 && Extent[0] < Extent[2] && Extent[1] < Extent[3]) {
      //   const Xmin = Extent[0],
      //     Ymin = Extent[1],
      //     Xmax = Extent[2],
      //     Ymax = Extent[3];
      //   if (
      //     inRange(-180, 180, Xmin) &&
      //     inRange(-180, 180, Xmax) &&
      //     inRange(-90, 90, Ymin) &&
      //     inRange(-90, 90, Ymax)
      //   ) {
      //     extentFlag = false;
      //   }
      // }
      // if (extentFlag) {
      //   ElMessage.warning('Extent数据书写错误');
      //   return false;
      // }
    }
    if (formData.value.dataType === '3') {
      configJson = {
        IsHandle: true,
        Method: 'LayerRele',
        Extent: extent.value,
      };
      if (!extent.value.includes('[EPSG:4326]')) {
        ElMessage.warning('Extent坐标系不正确');
        return false;
      }
    }
  }
  if (formData.value.fileType === 'tif-dem' && formData.value.dataType === '2') {
    configJson = {
      IsHandle: true,
      Method: 'LayerRele',
      Extent: extent.value,
    };
    if (!extent.value.includes('[EPSG:4326]')) {
      ElMessage.warning('Extent坐标系不正确');
      return false;
    }
  }

  const fileType = [
    'stp-step',
    'dxf',
    'obj',
    'fbx',
    'dgn',
    'skp',
    '3dxml',
    '3dm',
    'ifc',
    'nwd',
    'rvt',
  ];

  if (fileType.includes(formData.value.fileType)) {
    configJson = {
      ModelPrecision: ['skp', '3dxml'].includes(formData.value.fileType)
        ? 0
        : formData.value.ModelPrecision,
      IsDraco: formData.value.IsDraco,
      IsExportComponent: formData.value.IsExportComponent,
      ChangeType: changeType.value,
    };
  }
  const fData = new FormData();
  fData.set('fileResName', formData.value.fileResName);
  fData.set('fileType', formData.value.fileType);
  fData.set('fileCategoryId', formData.value.fileCategoryId);
  fData.set('configJson', configJson ? JSON.stringify(configJson) : '');
  fData.set('matDesp', formData.value.matDesp);
  fData.set('resCover', formData.value.resCover);

  if (uploadOptions.value === '2') {
    fData.set('fileName', fileCurrentObj.value.name);
    fData.set('fileSize', '0');
    fData.set('md5Code', 'DefLocalFileMd5Code');
    fData.set('sliceCout', '1');
    fData.set('defSliceSize', '52428800');
    fData.set('uploadMethod', 'local');
    uploadMethod.value = 'local';
  } else {
    fData.set('fileName', resFileList.value[0].name);
    fData.set('fileSize', resFileList.value[0].size);
    fData.set('md5Code', resFileList.value[0].md5Code);
    fData.set('sliceCout', resFileList.value[0].chunks.length);
    fData.set('defSliceSize', SIZE + '');
    fData.set('uploadMethod', 'remote');
    uploadMethod.value = 'remote';
  }
  const param = {
    data: fData,
  };
  // 上传资源
  resUploadParam(param).then(async (res: any) => {
    resourceId.value = res.resourceId;
    transId.value = res.transId;
    resourceName.value = formData.value.fileResName;

    if (uploadOptions.value === '2') {
      await LocalFileRun({
        params: {
          transId: res.transId,
          filePath: formData.value.filePath,
        },
      });
      upResourceDialogShow.value = true;
      // handleClose(true);
      // messageUtil.success('上传成功');
    } else {
      upResourceDialogShow.value = true;
    }
    // flag && emit('closeHandle', true);
  });
};

const handleClose = (refresh?: boolean) => {
  emit('closeHandle', refresh);
};

function getFile() {
  return fileIns;
}

const fileTypeKeyMap = {
  tif_dom: 'tif-dom',
  tif_dem: 'tif-dem',
  _3dtiles: '3dtiles',
} as any;

onMounted(async () => {
  formData.value.fileType = getFileType(props.fileType) || '';
  if (props.resource) {
    formItemConfig.value[1].disabled = true;
    dialogTitle.value = props.isReUpload ? '上传资源' : '编辑资源';
    formData.value.fileResName = props.resource.fileResName;
    formData.value.matDesp = props.resource.matDesp || '';
    formData.value.resCover = props.resource.resCover || '';
    formData.value.fileCategoryId = props.resource.categoryId || '';
    if (!props.isReUpload) {
      formItemConfig.value[2].label = '资源地址';
      formData.value.resUrl = 'test';
      formData.value.fileType = props.resource.fileType;
      formData.value.dataType = getDataType(props.resource);
      if (isEditTypeUpload) {
        getJsonConfig(props.resource);
      }
      if (props.resource.fileType === 'img') {
        setTimeout(() => {
          getImgConfig(props.resource);
        }, 500);
      }
    } else {
      formItemConfig.value[0].disabled = true;
      formItemConfig.value[4].disabled = true;
      formData.value.fileType = getFileType(props.resource.fileType) || '';
      formData.value.dataType = getDataType(props.resource);
    }
  }
  getCategoryTree(props.categoryId);
});

const getFileType = (fileType: any) => {
  if (['tif_dom', 'tif_dem', '_3dtiles'].includes(fileType)) {
    return fileTypeKeyMap[fileType];
  }
  return fileType;
};

const getDataType = (resource: any) => {
  if (['osgb', 'tif_dem', 'tif_dom'].includes(resource.fileType)) {
    if (resource.configJson) {
      extent.value = JSON.parse(resource.configJson).Extent;
    }
    console.log(extent.value);
    return resource.configJson ? '2' : '1';
  }
  return '';
};

const getJsonConfig = (resource: any) => {
  if (!resource.configJson) return;
  const {
    changeType: changeType1,
    IsExportComponent,
    ModelPrecision,
    IsDraco,
  } = JSON.parse(resource.configJson);
  changeType.value = changeType1;
  formData.value.IsDraco = IsDraco;
  formData.value.IsExportComponent = IsExportComponent;
  formData.value.ModelPrecision = Number(ModelPrecision);
};
const getImgConfig = (resource: any) => {
  formData.value.dataType = '1';
  if (!resource.configJson) return;
  const { leftLongitude, leftLatitude, rightLongitude, rightLatitude } = JSON.parse(
    resource.configJson
  );
  formData.value.leftPosition = { longitude: leftLongitude, latitude: leftLatitude };
  formData.value.rightPosition = { longitude: rightLongitude, latitude: rightLatitude };
  formData.value.dataType = '2';
};

const isEditTypeUpload = computed(() =>
  [
    'stp-step',
    'dxf',
    'obj',
    'fbx',
    'dgn',
    'skp',
    '3ds',
    '3dm',
    '3dxml',
    'ifc',
    'nwd',
    'rvt',
  ].includes(formData.value.fileType)
);

const acceptData = computed(() => {
  if (formData.value.fileType === 'img') {
    return updatedImgFormat.map((item) => '.' + item).join(',');
  } else if (!formData.value.fileType) {
    return [...updatedImgFormat, ...updatedFileFormat].map((item) => '.' + item).join(',');
  } else {
    return updatedFileFormat.map((item) => '.' + item).join(',');
  }
});
const closeChange = () => {
  handleClose(false);
  visibleCategoryTree.value = false;
};
const getExtent = (str: string) => {
  let extent = [];
  if (str.includes('EPSG')) {
    extent = str.replace('[EPSG:4326]', '').trim().split(',');
  } else {
    extent = str.trim().split(',');
  }

  return extent;
};
</script>

<style lang="less" scoped>
:deep(.el-textarea__inner) {
  height: 96px;
}
.select-data-type,
.position-input {
  display: flex;
  align-items: center;
  width: 100%;

  .el-select,
  .el-input {
    flex: 1;
    width: 50%;
  }

  .el-input:last-of-type {
    margin-left: 10px;
  }
}

.upload-res-file {
  width: 100%;
  :deep(.el-upload) {
    width: 100%;
    &-dragger {
      border: none;
      padding: 0px;
    }
  }
}
.large-file {
  width: 100%;
  .file {
    width: 100%;
    display: flex;
    align-items: center;
    .svg-icon {
      font-size: 20px;
      margin-right: 6px;
    }
    .close-icon {
      margin-left: auto;
      margin-right: 0px;
      cursor: pointer;
    }
  }
}
.up-load-res-file {
  height: 126px;
  flex: 1;
  border-radius: 8px;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  display: flex;
  border: 1px solid #e8e8e8;
  .svg-icon {
    font-size: 68px;
  }
  .el-upload__text {
    color: #585858;
    // font-weight: 600;
    font-size: 14px;
  }
  .el-upload__tip {
    font-size: 14px;
    color: #9a9a9a;
    margin-top: 0;
    padding: 0 10px;
  }
}
.cover-up-icon {
  width: 118px;
  height: 118px;
  border-radius: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid #e8e8e8;

  &.is-disabled {
    background: #e8e8e8;
  }

  .svg-icon {
    font-size: 30px;
  }
}
.avatar {
  width: 118px;
  height: 118px;
  border-radius: 4px;
}
.disabled-input {
  width: 100%;
  height: 32px;
  line-height: 32px;
  background-color: #e8e8e8;
  border-radius: 4px;
  padding: 0 11px;
}
.url-wrap {
  width: 100%;
  display: flex;
  align-items: center;
  .disabled-input {
    flex: 1;
  }
  .btn {
    flex: 0 0 65px;
    height: 32px;
    background: #0560fd;
    border-radius: 4px;
    font-size: 14px;
    color: #fff;
    text-align: center;
    margin-left: 10px;
    cursor: pointer;
  }
}

// 去掉展开和关闭的动画
:deep(.el-collapse-transition-enter-active),
:deep(.el-collapse-transition-leave-active) {
  transition: none;
}
:deep(.el-select-dropdown) {
  padding-top: 10px;
  .el-select-dropdown__item {
    padding: 0px;
    height: 60px;
    .select-item {
      border-radius: 4px;
      font-size: 14px;
      height: 60px;
      display: flex;
      flex-direction: column;
      margin-left: 12px;
      margin-right: 12px;
      padding-left: 12px;
      padding-right: 12px;
      justify-content: center;
      .select-item-value {
        color: #161616;
        line-height: 24px;
      }
      .select-item-tips {
        color: #9a9a9a;
        line-height: 24px;
      }
      .svg-class {
        position: absolute;
        right: 18px;
        width: 20px;
        height: 20px;
        display: none;
      }
    }
  }
  .el-select-dropdown__item.selected {
    .select-item {
      background-color: rgba(5, 96, 253, 0.12);
      .svg-class {
        display: block;
      }
    }
  }
}
// 数据处理
.data-processing {
  padding: 15px 0;
  width: 100%;
  .data-processing-select,
  .data-processing-switch {
    display: flex;
    height: 42px;
    line-height: 42px;
    margin-top: 10px;
    .select-term,
    .switch-term {
      width: 50%;
      display: flex;
      align-items: center;
      label {
        width: 100px;
        text-align: center;
        svg {
          vertical-align: middle;
        }
      }
    }
    .switch-term {
      text-align: right;
      label {
        width: 150px;
      }
    }
    .el-switch {
      margin-left: auto;
    }
  }
}
//资源文件上传
.local-upload {
  width: 100%;
}
.large-files-upload {
  width: 100%;
  :deep(.el-cascader) {
    width: 100%;
  }
}

.none {
  display: none;
}
.upload-form {
  .category-input {
    cursor: pointer;
    position: relative;
    height: 32px;
    width: 100%;
    border: 1px solid #e8e8e8;
    border-radius: 4px;
    padding: 0 10px;
    color: #161616;
    &.disabled {
      background-color: #e8e8e8;
    }
    .placeholder {
      color: #9a9a9a;
    }
    .svg-arrow {
      position: absolute;
      right: 10px;
      top: 10px;
      color: '#a8abb2';
      font-size: 12px;
    }
  }
  :deep(.el-form-item) {
    margin-bottom: 16px;
  }
  :deep(.el-form-item__label) {
    height: 32px;
    line-height: 32px;
    color: #585858;
  }
  :deep(.el-input) {
    height: 32px;
    .el-input__wrapper {
      height: 32px;
      .el-input__inner {
        height: 32px;
      }
    }
  }
}
.custom-radio-svg {
  vertical-align: middle;
}
.dialog-footer {
  display: flex;
  justify-content: center;
  .el-button {
    width: 65px;
    height: 32px;
    &.close {
      background-color: transparent;
      color: #0560fd;
    }
  }
}
// popover
:deep(.custom-popover) {
  border: none;
  padding: 10px 0;
  box-shadow: 0px 9px 28px 8px rgba(0, 0, 0, 0.05), 0px -4px 16px 0px rgba(0, 0, 0, 0.08),
    0px 3px 6px -4px rgba(0, 0, 0, 0.12);
  .el-tree {
    & > .el-tree-node {
      padding: 0 15px !important;
    }
    .el-tree-node {
      padding: 0;

      &.is-current[aria-expanded='false'] {
        background: #f5f7fa;
        color: #0560fd;
      }
      .el-tree-node__content {
        height: 38px;
        line-height: 38px;
        &:hover {
          background: #f5f7fa;
          color: #0560fd;
          .el-icon {
            color: #0560fd;
            &.is-leaf {
              color: transparent;
            }
          }
        }
        .el-checkbox {
          display: none;
        }
      }
    }
  }
  .none {
    display: none;
  }
}
// dark  popover
:deep(.dark.custom-popover) {
  &.is-light {
    background-color: #1d1d1d !important;
  }
  .el-tree {
    background-color: #1d1d1d;
    & > .is-current[aria-expanded='false'] {
      background: #1d1d1d !important;
    }
    .el-tree-node {
      &.is-current[aria-expanded='false'] {
        background: #153160;
        color: #ffffff;
      }
      &.is-current:focus {
        .el-tree-node__content {
          background: transparent !important;
        }
      }
      .el-tree-node__content {
        .el-tree-node__label {
          color: #fff;
        }
        &:hover,
        &.is-focus,
        &.is-focusable {
          background: #153160;
          color: #ffffff !important;
          .el-icon {
            color: #ffffff !important;
            &.is-leaf {
              color: transparent !important;
            }
          }
        }
      }
    }
  }
}
</style>
<style lang="less">
.center-detail {
  .el-dialog__body {
    padding: 24px 20px;
  }
  &.dark {
    .el-dialog__title {
      color: #dfdfdf;
    }
    .el-dialog__close {
      color: #dfdfdf;
    }
    .el-form-item__content > span {
      color: #878787;
    }
    .el-popper.is-light {
      background-color: transparent;
      border: none;
    }
    .select-term,
    .switch-term {
      color: #fff;
    }
    .el-upload-dragger {
      background-color: #1d1d1d;
    }
    .el-popper__arrow::before {
      background-color: #1d1d1d;
      border-color: #1d1d1d;
    }
    background-color: #2e2e2e;
    .el-input__inner {
      color: #dfdfdf;
    }
    .el-popper.is-light {
      background-color: transparent;
      border: none;
    }
    .el-select-dropdown {
      background-color: #1d1d1d;
      .select-item-value {
        color: #fff !important;
      }
      .el-select-dropdown__item,
      .el-select-dropdown__item {
        &:hover,
        &.hover {
          background-color: fade(#0560fd, 30);
          .select-item .select-item-value {
            color: #ffffff;
          }
        }
        &.selected {
          background-color: fade(#0560fd, 30);
          .select-item {
            background-color: transparent;
            .select-item-value {
              color: #ffffff;
            }
          }
        }
      }
    }

    .el-radio.el-radio--large .el-radio__label {
      color: #dfdfdf;
    }
    .upload-form {
      .el-form-item__label {
        color: #dfdfdf;
      }
      .category-input {
        border: 1px solid #464646;
        color: #dfdfdf;
      }
      .el-input {
        .el-input__wrapper {
          background: #303030;
          box-shadow: none;
          border: 1px solid #464646;
        }
      }
      .up-load-res-file {
        border: 1px solid #464646;
        background-color: #2e2e2e;
        .el-upload__text {
          color: #dfdfdf;
        }
        .el-upload__tip {
          color: #878787;
        }
      }
      .cover-up-icon {
        border: 1px solid #464646;
        background: #303030;
      }

      .el-textarea__inner {
        border: 1px solid #464646;
        background: #303030;
        box-shadow: none;
      }
    }
  }
}
</style>
